// pages/my-processing/my-processing.ts
import { getMyProcessingList } from '../../../api/publish';
import { PAGES, goToPage } from '../../../config/pages.js';
import { formatDate } from '../../../utils/time';

Page({
  data: {
    searchValue: '',
    processingList: [] as any[],
    loading: false,
    page: 1,
    limit: 20,
    hasMore: true
  },

  onLoad() {
    this.loadProcessing();
  },

  onShow() {
    // 刷新数据
    this.loadProcessing(true);
  },

  // 页面滚动到底部时触发
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadProcessing();
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadProcessing(true).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载我的加工列表
  async loadProcessing(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        processingList: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        page: this.data.page,
        limit: this.data.limit
      };

      // 添加搜索关键词参数
      if (this.data.searchValue && this.data.searchValue.trim()) {
        params.keyword = this.data.searchValue.trim();
      }

      const res = await getMyProcessingList(params);
      
      if (res.status === 200 && res.data) {
        // 格式化日期
        const formattedList = res.data.list.map((item: any) => ({
          ...item,
          formatted_date: formatDate(item.add_time || item.create_time)
        }));
        
        const newProcessingList = refresh ? formattedList : [...this.data.processingList, ...formattedList];
        
        this.setData({
          processingList: newProcessingList,
          hasMore: newProcessingList.length < (res.data.count || 0),
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('加载我的加工列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadProcessing(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadProcessing();
    }
  },

  // 搜索输入
  onSearchInput(e: any) {
    this.setData({
      searchValue: e.detail.value
    });
  },

  // 执行搜索
  performSearch(e: any) {
    // 如果是事件对象，获取输入值；如果是字符串，直接使用
    const keyword = typeof e === 'string' ? e : (e.detail?.value || '');
    this.loadProcessing(true);
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchValue: ''
    });
    this.loadProcessing(true);
  },

  // 跳转到加工详情
  goToDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    goToPage(PAGES.MY_PROCESSING_DETAIL, { id });
  },

  // 编辑加工
  editProcessing(e: any) {
    const id = e.currentTarget.dataset.id;
    goToPage(PAGES.MY_PROCESSING_EDIT, { id });
  },

  // 删除加工
  deleteProcessing(e: any) {
    const id = e.currentTarget.dataset.id;
    const { deletePublish } = require('../../../api/publish');
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条加工信息吗？',
      confirmText: '确定删除',
      confirmColor: '#d54941',
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await deletePublish(id);
            if (result.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              this.loadProcessing(true);
            } else {
              wx.showToast({
                title: result.msg || '删除失败',
                icon: 'none'
              });
            }
          } catch (error: any) {
            console.error('删除加工失败:', error);
            wx.showToast({
              title: typeof(error) === 'string' ? error : (error?.message || '删除失败'),
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  }
});

